package CardGateway;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import paymentgateway.PaymentGatewayServer;


/**
 *
 * @author pro
 */
@WebServlet(name = "GatewayServlet", urlPatterns = {"/GatewayServlet"})
public class GatewayServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private String cardHolderName;
    private String cardNumber;
    private Socket socket;
    protected InputStream iStream;            // Instance variables
    protected OutputStream oStream;
    private String returnedStatus;
    private String url = "localhost";
    private int port = 10003;
   String servStr;
    

    
    /**
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {



        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            cardHolderName = request.getParameter("Cardholdername");
            cardNumber = request.getParameter("Cardnumber");
            
           String name = request.getParameter("ShippingName");
           String shippingAddress = request.getParameter("ShippingAddress");
           String billingAddress =  request.getParameter("BillingAddress");
           String shippingCity = request.getParameter("ShippingCity");
           String shippingState = request.getParameter("ShippingState");
           String shippingZip = request.getParameter("ShippingZip");
           String phone = request.getParameter("Phone");
           String email = request.getParameter("Email");
           String billingCity = request.getParameter("BillingCity");
           String billingState = request.getParameter("BillingState");
           String billingZip = request.getParameter("BillingZip");
           String expMonth = request.getParameter("expmonth");
           String expYear = request.getParameter("expyear");
           
           request.setAttribute("ShippingName", name);
           request.setAttribute("Cardholdername", cardHolderName);
           request.setAttribute("Cardnumber", cardNumber);
           request.setAttribute("ShippingAddress", shippingAddress);
           request.setAttribute("BillingAddress", billingAddress);
           request.setAttribute("ShippingCity", shippingCity);
           request.setAttribute("ShippingState", shippingState);
           request.setAttribute("ShippingZip", shippingZip);
           request.setAttribute("Phone", phone );
           request.setAttribute("Email", email);
           request.setAttribute("BillingCity", billingCity);
           request.setAttribute("BillingState", billingState);
           request.setAttribute("BillingZip", billingZip);
           request.setAttribute("expmonth", expMonth);
           request.setAttribute("expyear", expYear);
        
                       
            
           // PaymentGatewayServer a=new PaymentGatewayServer(port,1);
            //PaymentGatewayServer server = new PaymentGatewayServer(10001, 3);
     //server.start();
     
     //GatewayClient client = new GatewayClient("localhost", 10002);
     // client.start();
            
            processCardData();
            
            
            if(servStr.equalsIgnoreCase("Congratulations..Card Verified")){
RequestDispatcher dispatcher=getServletContext().getRequestDispatcher("/reviewcheckout.jsp");
        dispatcher.forward(request,response);   
            }
            
            else{
               RequestDispatcher dispatcher=getServletContext().getRequestDispatcher("/billingcheckout.jsp");
        dispatcher.forward(request,response);   
            }
            /* TODO output your page here. You may use following sample code. 
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet GatewayServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet GatewayServlet at " + request.getContextPath() + "</h1>");
            out.println("<p><h2>Response from server: "+returnedStatus+"</h2></p>");
            out.println("</body>");
            out.println("</html>");
         * 
         */
        } finally 
        
        {
            out.close();
                 
           
        }
    }

    private void processCardData() {
        try {
            socket = new Socket(url, port);
            System.out.println("CLIENT: connected to " + url + ":" + port);
            requestService(socket);
            socket.close();
            System.out.println("CLIENT: connection closed");
        } catch (Exception e) {
            e.printStackTrace();
            returnedStatus = "Socket Error - could not validate";
        }

    }
    

    /**
     * requestService() implements the details of the service request. In this
     * case it accepts a line of input from the user and passes it along to the
     * server. The protocol with the server requires that the server say "Hello"
     * first.
     *
     * @param socket -- the Socket connection to the server
     */
    protected void requestService(Socket socket) throws IOException {
         servStr = readFromSocket(socket);          // Check for "Hello"
        System.out.println("SERVER: " + servStr);         // Report the server's response
        //System.out.println("CLIENT: type a line or 'goodbye' to quit"); // Prompt the user
        if (servStr.substring(0, 5).equals("Hello")) {
            String userStr = "";

            userStr = cardHolderName+":"+cardNumber+":1";   
            writeToSocket(socket, userStr + "\n");          // Send it to server
            servStr = readFromSocket(socket);               // Read the server's response
            returnedStatus = servStr;
                   
            System.out.println("SERVER: " + servStr);       // Report the server's response
        }
    } // requestService()

    /**
     * readFromSocket() reads one line of data from a socket and returns it as a
     * string
     *
     * @param sock -- a reference to the Socket object
     */
    public String readFromSocket(Socket sock) throws IOException {
        iStream = sock.getInputStream();
        String str = "";
        char c;
        while ((c = (char) iStream.read()) != '\n') {
            str = str + c + "";
        }
        return str;
    }

        /**
     *  writeToSocket() reads a String to a given socket
     *  @param sock -- a reference to the Socket object
     *  @param str -- the string to be written
     */
    public void writeToSocket(Socket sock, String str) throws IOException {
        oStream = sock.getOutputStream();
        if (str.charAt( str.length() - 1 ) != '\n')
            str = str + '\n';
        for (int k = 0; k < str.length() ; k++)
            oStream.write(str.charAt(k));
    } // writeToSocket
    
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
